package jwcb.javapjframework.gateway.filter;

import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jwcb.javapjframework.common.core.utils.ServletUtil;
import jwcb.javapjframework.common.core.utils.StringUtil;
import jwcb.javapjframework.common.domain.constants.SecurityConstants;
import jwcb.javapjframework.common.domain.domain.ResultCode;
import jwcb.javapjframework.common.redis.RedisService.service.RedisService;
import jwcb.javapjframework.common.security.service.TokenService;
import jwcb.javapjframework.common.security.utils.JwtUtil;
import jwcb.javapjframework.common.security.utils.SecurityUtil;
import jwcb.javapjframework.gateway.config.IgnoreWhiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisService redisService;


    @Autowired
    private TokenService tokenService;

    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始过滤");

        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路由
        String url = request.getURI().getPath();
        if(StringUtil.matches(url,ignoreWhiteProperties.getWhites())) {
            return chain.filter(exchange);
        }
        // 鉴权
        String token = SecurityUtil.getToken( request);
        if(StringUtil.isEmpty(token)) {
            return unauthorizedResp(exchange,ResultCode.TOKEN_EMPTY);
        }
        // 根据令牌获取有效信息
        Claims claims = JwtUtil.parseToken(token);
        if(claims == null) {
            return unauthorizedResp(exchange,ResultCode.TOKEN_CHECK_FAILED);
        }
        String userKey = JwtUtil.getUserKey(claims);
        String userId = JwtUtil.getUserId(claims);
        String userFrom = JwtUtil.getUserFrom(claims);
        String userName = JwtUtil.getUserName(claims);
        String userIdentity = JwtUtil.getUserIdentity(claims);
        if(StringUtil.isEmpty(userKey) || StringUtil.isEmpty(userId) || StringUtil.isEmpty(userFrom)|| StringUtil.isEmpty(userIdentity)) {
            return unauthorizedResp(exchange,ResultCode.TOKEN_CHECK_FAILED);
        }
        String cacheKey = tokenService.getCacheKey(userKey,Long.valueOf(userId),userFrom);
        if (!redisService.hasKey(cacheKey)) {
            return unauthorizedResp(exchange,ResultCode.LOGIN_STATUS_OVERTIME);
        }

        // 设置用户信息到请求头
        ServerHttpRequest.Builder mutate = request.mutate();
        ServletUtil.addHeader(mutate, SecurityConstants.USER_KEY,userKey);
        ServletUtil.addHeader(mutate, SecurityConstants.USER_ID,userId);
        ServletUtil.addHeader(mutate, SecurityConstants.USERNAME,userName);
        ServletUtil.addHeader(mutate,SecurityConstants.USER_FROM,userFrom);
        // 加上Header信息之后继续执行
        log.info("继续执行");
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    /**
     * 未授权
     * @param exchange ServerWebExchange
     * @param resultCode 结果码
     */
    private Mono<Void> unauthorizedResp(ServerWebExchange exchange, ResultCode resultCode) {
        log.warn("[鉴权处理异常]请求路径:{}",exchange.getRequest().getPath());
        Integer code = Integer.valueOf(String.valueOf(resultCode.getCode()).substring(0, 3));
        return ServletUtil.webFluxResponseWriter(exchange.getResponse(), HttpStatus.valueOf(code),
                resultCode.getMsg(),resultCode.getCode());
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
